﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPSnippets.FaceBookAPI;
using ASPSnippets.GoogleAPI;
using ASPSnippets.LinkedInAPI;
using ImpactWorks.FBGraph.Core;
using ImpactWorks.FBGraph.Interfaces;

namespace oAuth2
{
    public partial class Default : System.Web.UI.Page
    {
        sqlHelper asqSqlHelper = new sqlHelper();
        ImpactWorks.FBGraph.Connector.Facebook facebook = new ImpactWorks.FBGraph.Connector.Facebook();
        protected void Page_Load(object sender, EventArgs e)
        {
            //Setting up the facebook object

            facebook.AppID = "315944655224169";
            facebook.CallBackURL = "http://trustyn.com/";
            facebook.Secret = "c795723a2a61d578179aba8f96cc260f";

            //Setting up the permissions
            List<FBPermissions> permissions = new List<FBPermissions>() {
            
                            FBPermissions.email, //To get user's email address
                            FBPermissions.user_about_me, // to read about me
                            FBPermissions.user_birthday, // Get DOB
                            FBPermissions.user_education_history, //get education
                            FBPermissions.user_location, //Location of user
                            FBPermissions.user_relationships,//relationship status of user
                            FBPermissions.user_work_history,//Workhistory of user
                            FBPermissions.user_website,//website entered in fb Profilr
                            FBPermissions.create_event,
                            FBPermissions.user_events,
                            FBPermissions.user_status,
                            FBPermissions.read_stream,
                            FBPermissions.friends_events,
                            FBPermissions.publish_stream
                        };

            //Pass the permissions object to facebook instance
            facebook.Permissions = permissions;
            
            LinkedInConnect.APIKey = "753lessv22u6my";
            LinkedInConnect.APISecret = "1Eq3omeSaNFcY0dF";
            LinkedInConnect.RedirectUrl = Request.Url.AbsoluteUri.Split('?')[0];


            GoogleConnect.ClientId = "660016173034-98tmg9grprjuuv7noidahfigb28iqh9s.apps.googleusercontent.com";
            GoogleConnect.ClientSecret = "W07XaEkOKFy27ZbvPDmVEdlI";
            GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];

            if (!IsPostBack)
            {
                if (Session["Button"] != null)
                {
                    if (Session["Button"].ToString().Trim() == "1")
                    {
                        
                        if (String.IsNullOrEmpty(Request.QueryString["code"]))
                        {
                            String authLink = facebook.GetAuthorizationLink();

                            Response.Redirect(authLink);
                        }
                        else
                        {
                            //Get the code returned by facebook
                            string Code = Request.QueryString["code"];

                            //process code for auth token
                            facebook.GetAccessToken(Code);

                            //Get User info
                            FBUser currentUser = facebook.GetLoggedInUserInfo();
                            //Link share

                            IFeedPost FBpost = new FeedPost();

                            //Custom Action that we can add
                            FBpost.Action = new FBAction { Name = "view my website", Link = "http://trustyn.com/" };
                            FBpost.Caption = "Share";
                            FBpost.Description = "Desc";
                            FBpost.ImageUrl = "http://trustyn.com/img/wall.png";
                            FBpost.Message = ConfigurationManager.AppSettings["message"];
                            FBpost.Name = ConfigurationManager.AppSettings["message"];
                            FBpost.Url = "http://trustyn.com/";

                            var postID = facebook.PostToWall(currentUser.id.GetValueOrDefault(), FBpost);

                            FaceBookUser faceBookUser = new FaceBookUser();
                            faceBookUser.Email = currentUser.email;
                            faceBookUser.Name = currentUser.name;
                            faceBookUser.first_name = currentUser.first_name;
                            faceBookUser.last_name = currentUser.last_name;
                            if (!asqSqlHelper.existAcount(faceBookUser.Email, "facebook"))
                            {
                                asqSqlHelper.InsertAccount(faceBookUser);
                            }
                            Session["UserLogin"] = faceBookUser.Name;
                            Session["Button"] = null;
                        }
                        
                    }
                    else if (Session["Button"].ToString().Trim() == "2")
                    {
                        if (LinkedInConnect.IsAuthorized)
                        {
                            DataSet ds = LinkedInConnect.Fetch();

                            var aLinkedInAccount = new LinkedInAccount();
                            aLinkedInAccount.fisrt_name = ds.Tables["person"].Rows[0]["first-name"].ToString();
                            aLinkedInAccount.last_name = " " + ds.Tables["person"].Rows[0]["last-name"].ToString();
                            aLinkedInAccount.email_address = ds.Tables["person"].Rows[0]["email-address"].ToString();
                            aLinkedInAccount.headline = ds.Tables["person"].Rows[0]["headline"].ToString();
                            aLinkedInAccount.industry = ds.Tables["person"].Rows[0]["industry"].ToString();
                            aLinkedInAccount.id = ds.Tables["person"].Rows[0]["id"].ToString();
                            
                            if (!asqSqlHelper.existAcount(aLinkedInAccount.email_address, "linkedin"))
                            {
                                asqSqlHelper.InsertAccount(aLinkedInAccount);
                            }
                            Session["UserLogin"] = aLinkedInAccount.fisrt_name;
                        }
                        Session["Button"] = null;
                    }
                    else if (Session["Button"].ToString().Trim() == "3")
                    {
                        if (!string.IsNullOrEmpty(Request.QueryString["code"]))
                        {
                            GoogleConnect.API = EnumAPI.GooglePlus;
                            string code = Request.QueryString["code"];
                            string json = GoogleConnect.Fetch("me", code, 500);
                            GoogleProfile profile = new JavaScriptSerializer().Deserialize<GoogleProfile>(json);
                            if (
                                !asqSqlHelper.existAcount(profile.Emails.Find(email => email.Type == "account").Value,
                                    "linkedin"))
                            {
                                asqSqlHelper.InsertAccount(profile);
                            }
                            Session["UserLogin"] = profile.DisplayName;
                        }
                        if (Request.QueryString["error"] == "access_denied")
                        {
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')",
                                true);
                        }

                        Session["Button"] = null;
                    }
                }
            }
        }

        protected void btnFacebook_OnClick(object sender, ImageClickEventArgs e)
        {

            Session["Button"] = 1;
            if (String.IsNullOrEmpty(Request.QueryString["code"]))
            {
                String authLink = facebook.GetAuthorizationLink();

                Response.Redirect(authLink);
            }
        }


        protected void btnGoogle_OnClick(object sender, ImageClickEventArgs e)
        {
            Session["Button"] = 3;
            GoogleConnect.Authorize("profile", "email");
        }

        protected void btnLinkedIn_OnClick(object sender, ImageClickEventArgs e)
        {
            Session["Button"] = 2;
            LinkedInConnect.Authorize();
        }
    }

    public class FaceBookUser
    {
        public string Id { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string Name { get; set; }
        public string UserName { get; set; }
        public string PictureUrl { get; set; }
        public string Email { get; set; }
    }


    public class LinkedInAccount
    {
        public string fisrt_name { get; set; }

        public string last_name { get; set; }

        public string headline { get; set; }

        public string industry { get; set; }

        public string picture_url { get; set; }

        public string email_address { get; set; }

        public string id { get; set; }
    }

    public class GoogleProfile
    {
        public string Id { get; set; }
        public string DisplayName { get; set; }
        public Image Image { get; set; }
        public List<Email> Emails { get; set; }
        public string Gender { get; set; }
        public string ObjectType { get; set; }
    }

    public class Email
    {
        public string Value { get; set; }
        public string Type { get; set; }
    }

    public class Image
    {
        public string Url { get; set; }
    }
}